package cn.flying.cloud.base.core.configuration;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

/**
 * 解决前后端json格式转换问题
 * 对应json日期格式有几种方式：
 * yml中配置spring.jackson.date-format和time-zone
 * Jackson2ObjectMapperBuilderCustomizer对象
 * Jackson2ObjectMapperBuilder对象
 *
 * @author: admin
 * @date: 2022年06月22日 00:21
 * @version: 1.0
 */
@Configuration
public class JacksonAutoConfiguration {

    /**
     * 配置指定的转换类型
     * 指定为默认bean，防止有多个
     */
    @Primary
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            // Jackson全局转化long类型为String，解决jackson序列化时传入前端Long类型缺失精度问题
            builder.serializerByType(BigInteger.class, ToStringSerializer.instance);
            builder.serializerByType(Long.class, ToStringSerializer.instance);
            builder.serializerByType(Long.TYPE, ToStringSerializer.instance);

            //全局时间格式化 去掉 "T"
            builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            // 解决Date类型
            // 自定义日期格式
            builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 设置时区
            builder.timeZone(TimeZone.getTimeZone("GMT+8"));

            // 注册Java 8日期和时间模块
//            JavaTimeModule javaTimeModule = new JavaTimeModule();
//            builder.modules(javaTimeModule);

        };
    }
}